<template>
  <div>
    <div class="content-header">
      <h1>系统设置<small>权限管理</small></h1>
      <el-breadcrumb separator-class="el-icon-arrow-right" class="breadcrumb">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>系统设置</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="app-container">
      <div class="box">
        <div class="filter-container">
          <el-input
            placeholder="名称/关键字"
            v-model="pagination.queryString"
            style="width: 200px"
            class="filter-item"
            @keyup.enter.native="handleFilter"
          ></el-input>
          <el-button @click="findPageByCondition" class="dalfBut"
            >查询</el-button
          >
          <el-button type="primary" class="butT" @click="handleCreate()"
            >新建</el-button
          >
        </div>
        <el-table
          size="small"
          current-row-key="id"
          :data="dataList"
          stripe
          highlight-current-row
        >
          <el-table-column
            type="index"
            align="center"
            label="序号"
          ></el-table-column>
          <el-table-column
            prop="name"
            label="角色名称"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="keyword"
            label="关键字"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="description"
            label="备注"
            align="center"
          ></el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button
                type="primary"
                size="mini"
                @click="handleUpdate(scope.row)"
                >编辑</el-button
              >
              <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-container">
          <el-pagination
            class="pagiantion"
            @current-change="handleCurrentChange"
            :current-page="pagination.currentPage"
            :page-size="pagination.pageSize"
            layout="total, prev, pager, next, jumper"
            :total="pagination.total"
          >
          </el-pagination>
        </div>
        <!-- 新增标签弹层 -->
        <div class="add-form">
          <el-dialog title="新增角色" :visible.sync="dialogFormVisible">
            <template>
              <el-tabs v-model="activeName" type="card">
                <el-tab-pane label="基本信息" name="first">
                  <el-form
                    :model="formData"
                    ref="dataAddForm"
                    label-position="right"
                    label-width="100px"
                    :rules="rules"
                  >
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="名称" prop="name">
                          <el-input v-model="formData.name" />
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="关键字">
                          <el-input v-model="formData.keyword" />
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="24">
                        <el-form-item label="备注">
                          <el-input
                            v-model="formData.description"
                            type="textarea"
                          ></el-input>
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </el-form>
                </el-tab-pane>
                <el-tab-pane label="权限信息" name="second">
                  <div class="checkScrol">
                    <table class="datatable">
                      <thead>
                        <tr>
                          <th>选择</th>
                          <th>权限名称</th>
                          <th>权限关键字</th>
                          <th>权限说明</th>
                        </tr>
                      </thead>
                      <tbody>
                        <tr v-for="c in permissionTableDate" v-bind:key="c">
                          <td>
                            <input
                              :id="c.id"
                              v-model="permissionIds"
                              type="checkbox"
                              :value="c.id"
                            />
                          </td>
                          <td>
                            <label :for="c.id">{{ c.name }}</label>
                          </td>
                          <td>
                            <label :for="c.id">{{ c.keyword }}</label>
                          </td>
                          <td>
                            <label :for="c.id">{{ c.description }}</label>
                          </td>
                        </tr>
                      </tbody>
                    </table>
                  </div>
                </el-tab-pane>
                <el-tab-pane label="菜单信息" name="thirdly">
                  <div class="custom-tree-container">
                    <div class="block">
                      
                      <el-tree
                        :data="data"
                        show-checkbox
                        node-key="id"
                        default-expand-all
                        :expand-on-click-node="false"
                        :render-content="renderContent">
                      </el-tree>
                    </div>
                  </div>
                </el-tab-pane>
              </el-tabs>
            </template>
            <div slot="footer" class="dialog-footer">
              <el-button @click="dialogFormVisible = false">取消</el-button>
              <el-button type="primary" @click="handleAdd('dataAddForm')">确定</el-button>
            </div>
          </el-dialog>
        </div>

        <!-- 编辑标签弹层 -->
        <div class="add-form">
          <el-dialog title="编辑角色" :visible.sync="dialogFormVisible4Edit">
            <template>
              <el-tabs v-model="activeName" type="card">
                <el-tab-pane label="基本信息" name="first">
                  <el-form
                    :model="formData"
                    ref="dataEditForm"
                    :rules="rules"
                    label-position="right"
                    label-width="100px"
                  >
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="名称" prop="name">
                          <el-input v-model="formData.name" />
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="关键字">
                          <el-input v-model="formData.keyword" />
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="24">
                        <el-form-item label="备注">
                          <el-input
                            v-model="formData.description"
                            type="textarea"
                          ></el-input>
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </el-form>
                </el-tab-pane>
                <el-tab-pane label="权限信息" name="second">
                  <div class="checkScrol">
                    <table class="datatable">
                      <thead>
                        <tr>
                          <th>选择</th>
                          <th>权限名称</th>
                          <th>权限关键字</th>
                          <th>权限备注</th>
                        </tr>
                      </thead>
                      <tbody>
                        <tr v-for="c in permissionTableDate" v-bind:key="c">
                          <td>
                            <input
                              :id="c.id"
                              v-model="permissionIds"
                              type="checkbox"
                              :value="c.id"
                            />
                          </td>
                          <td>
                            <label :for="c.id">{{ c.name }}</label>
                          </td>
                          <td>
                            <label :for="c.id">{{ c.keyword }}</label>
                          </td>
                          <td>
                            <label :for="c.id">{{ c.description }}</label>
                          </td>
                        </tr>
                      </tbody>
                    </table>
                  </div>
                </el-tab-pane>
                <el-tab-pane label="菜单信息" name="thirdly">
                  <div class="checkScrol">
                    <table class="datatable">
                      <thead>
                        <tr>
                          <th>选择</th>
                          <th>项目名称</th>
                          <th>项目备注</th>
                        </tr>
                      </thead>
                      <tbody>
                        <tr v-for="c in menuTableDate" v-bind:key="c">
                          <td>
                            <input
                              :id="c.id"
                              v-model="menuIds"
                              type="checkbox"
                              :value="c.id"
                            />
                          </td>
                          <td>
                            <label :for="c.id">{{ c.name }}</label>
                          </td>
                          <td>
                            <label :for="c.id">{{ c.description }}</label>
                          </td>
                        </tr>
                      </tbody>
                    </table>
                  </div>
                </el-tab-pane>
              </el-tabs>
            </template>
            <div slot="footer" class="dialog-footer">
              <el-button @click="dialogFormVisible4Edit = false"
                >取消</el-button
              >
              <el-button type="primary" @click="handleEdit('dataEditForm')">确定</el-button>
            </div>
          </el-dialog>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    const data = '';
      
    return {
      data: JSON.parse(JSON.stringify(data)),
        data: JSON.parse(JSON.stringify(data)),
      activeName: "first", //添加/编辑窗口Tab标签名称
      pagination: {
        //分页相关属性
        currentPage: 1,
        pageSize: 5,
        total: 100,
        queryString: null,
      },
      dataList: [], //列表数据
      formData: {}, //表单数据
      permissionTableDate: [], //新增和编辑表单中对应的权限列表数据
      menuTableDate: [], //新增和编辑表单中对应的菜单列表数据
      permissionIds: [], //新增和编辑表单中权限对应的复选框，基于双向绑定可以进行回显和数据提交
      menuIds: [], //新增和编辑表单中权限对应的复选框，基于双向绑定可以进行回显和数据提交
      dialogFormVisible: false, //控制添加窗口显示/隐藏
      dialogFormVisible4Edit: false, //控制编辑窗口显示/隐藏
      rules: {
        //校验规则
        keyword: [
          { required: true, message: "角色关键字为必填项", trigger: "blur" },
          { min: 2, max: 10, message: "长度在 2 到 10个字符", trigger: "blur" },
        ],
        name: [
          { required: true, message: "角色名称为必填项", trigger: "blur" },
          { min: 2, max: 10, message: "长度在 2 到 10个字符", trigger: "blur" },
        ],
      },
    };
  },

  created() {
    this.findPage()
  },
  methods: {

      append(data) {
        const newChild = { id: id++, label: 'testtest', children: [] };
        if (!data.children) {
          this.$set(data, 'children', []);
        }
        data.children.push(newChild);
      },

      remove(node, data) {
        const parent = node.parent;
        const children = parent.data.children || parent.data;
        const index = children.findIndex(d => d.id === data.id);
        children.splice(index, 1);
      },

      renderContent(h, { node, data, store }) {
        return (
          <span class="custom-tree-node">
            <span>{node.label}</span>
            <span>
              <el-button size="mini" type="text" on-click={ () => this.append(data) }>Append</el-button>
              <el-button size="mini" type="text" on-click={ () => this.remove(node, data) }>Delete</el-button>
            </span>
          </span>);
      },
  
    //清除当前窗口数据
    clear(){
        this.menuIds = []
        this.permissionIds = []
        this.activeName = "first"
        this.formData = {}
        this.permissionTableDate = []
        this.menuTableDate = []
    },
    //编辑弹窗
    handleUpdate(row){
        this.dialogFormVisible4Edit = true
        this.activeName = "first"
        //回显
        let rowdata = JSON.stringify(row);
        this.formData = JSON.parse(rowdata)
        this.$http.get("api/system/findAllRole").then((res)=>{
            this.permissionTableDate = res.data.data
        })
         this.$http.get("api/system/findAllMenu").then((res)=>{
            this.menuTableDate = res.data.data
        })
        this.$http.get("api/system/findPermissionIdsAndMenuIdsByRoleId/"+row.id).then((res)=>{
            this.permissionIds = res.data.data.permissionIds
            this.menuIds=res.data.data.menuIds
        })
        
    },
    //编辑确认
    handleEdit(dataEditForm){
        this.handleAdd(dataEditForm)
    },
    //新增 弹窗 查询所有权限信息  赋值 permissionTableDate
    handleCreate(){
        this.clear()
        this.dialogFormVisible = true
        this.$http.get("api/system/findAllRole").then((res)=>{
            this.permissionTableDate = res.data.data
        })
         this.$http.get("api/system/findAllMenu").then((res)=>{
            const data  = res.data.data
        })
    },
    handleAdd(dataAddForm){
        // 校验  表单
        this.$refs[dataAddForm].validate((valid)=>{
            if(valid){
                //checkbox 必须勾选
                if(this.permissionIds.length==0){
                    this.$message.warning("至少勾选一项权限")
                    this.activeName = "second"
                    return
                }else{
                    this.formData.permissionIds = this.permissionIds
                    this.formData.menuIds = this.menuIds
                    //数据合法
                    this.$http.post("api/system/saveOrUpdateOrDeleteRole",this.formData).then((res)=>{
                        if(res.data.flag){
                            //添加成功 or 修改成功
                            this.$message.success("提交成功！")
                            this.dialogFormVisible = false
                            this.dialogFormVisible4Edit = false
                            this.findPage()
                        }else{
                            this.$message.error("提交失败！")
                        }
                    })
                    
                }
            }else{
                this.$message.error("请按要求填写")
            }
        })
    },
    // 条件分页查询
    findPageByCondition(){
        this.pagination.currentPage = 1;
        this.findPage()
    },
    //页码变化
    handleCurrentChange(curpage){
        this.pagination.currentPage = curpage;
        this.findPage()
    },
    //分页查询
    findPage() {
      this.$http.post("api/system/findPageRole", this.pagination).then((res) => {
        if (res.data.flag) {
          this.pagination.total = res.data.data.total;
          this.dataList = res.data.data.rows;
          //  this.dataList=res.data.data
          //  alert(JSON.stringify(res.data.data))
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    //删除
    handleDelete(row){
        this.$confirm('此操作将永久删除该条目, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
            if(this.pagination.total%this.pagination.pageSize==1){
                this.pagination.currentPage = this.pagination.currentPage-1;
            }
            this.$http.post("api/system/deleteRole/"+row.id).then((res)=>{
                if(res.data.flag){
                        this.$message.success("删除成功！");
                        this.dialogFormVisible4Edit = false;
                        this.findPage();
                }else{
                        this.$message.error("删除失败！")
                    }
            })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
    })}
  },
};
</script>


<style scoped>
.datatable {
  position: relative;
  box-sizing: border-box;
  -webkit-box-flex: 1;
  width: 100%;
  max-width: 100%;
  font-size: 14px;
  color: rgb(96, 98, 102);
  overflow: hidden;
  flex: 1 1 0%;
}
.datatable td,
.datatable th {
  padding: 12px 0;
  min-width: 0;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  text-overflow: ellipsis;
  vertical-align: middle;
  position: relative;
  text-align: left;
}
.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
</style>
